<template>
  <div class="search">
    
      <el-row :gutter="15">
        <el-form ref="elForm" :model="queryParams"  size="medium" label-width="120px">
          <el-col :span="30">
            <el-row>
              <el-col :span="12">
                <el-form-item label="采购员:"  prop = "purchaser">
                      <el-select class="inputplace"
                       v-model="queryParams.purchaser"
                        placeholder="请选择活动区域" 
                        @change="getQueryFrom()"
                        @clear="getQueryFrom()"
                        clearable>
                        <el-option
                          v-for="item in this.purchaserDict"
                          :key="item.dictCode"
                          :label="item.dictLabel"
                          :value="item.dictLabel">
                        </el-option>
                      </el-select>
                    </el-form-item>
              </el-col>
              
              <el-col :span="12">
                  <el-form-item  label="采购日期范围:" label-width="120px">
                    <el-date-picker
                      v-model="queryParams.purchaseDate"
                      align="right"
                      type="date"
                      placeholder="选择日期"
                      :picker-options="pickerOptionsdate"
                      @change="getQueryFrom()"
                      @clear="getQueryFrom()"
                      value-format="yyyy-MM-dd"
                      clearable>
                    </el-date-picker>
                  </el-form-item>
              </el-col>
              
              
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="采购下单名称:" prop="field108" label-width="120px">
                  <el-autocomplete
                    v-model="queryParams.orderName"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入内容"
                    @select="handleSelect"
                    @clear="getQueryFrom()"
                    clearable
                    ></el-autocomplete>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="采购订单号:" prop="field102" label-width="120px">
                  <el-autocomplete
                    class="inline-input"
                    v-model="queryParams.orderNumber"
                    :fetch-suggestions="querySearchAsync1"
                    placeholder="请输入内容"
                    @select="handleSelect2"
                    @clear="getQueryFrom()"
                    focus="getQueryFrom"
                    clearable
                    ></el-autocomplete>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          
        </el-form>

      </el-row>
     
      <div class = "infotable">
        <!-- 操作按钮 -->
        <div class = "infotable_handerchild">
          <el-button  type="primary" @click="addHanderPop = true">新增</el-button>
          <el-button  type="primary" :disabled="editBotton" @click="editHanderPop= true">修改</el-button>
          <el-button type="danger" :disabled="deleteBotton" @click="deletetable()">删除</el-button>
          <el-button type="info" @click="upload.open=true">导入</el-button>
          <el-button type="info"  @click="importData()">导出</el-button>
        </div>
        <div class = "infotable_handerchild"  style = "min-height:600px ;">
          <el-table
          ref="multipleTable"
          height="650"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
          :data="tableData"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
          prop="purchaser"
          label="采购员">
          </el-table-column>
          <el-table-column
            prop="purchaseDate"
            label="采购日期">
          </el-table-column>
          <el-table-column
            prop="orderName"
            label="采购下单名称">
          </el-table-column>
          <el-table-column
            prop="orderNumber"
            label="采购订单号">
          </el-table-column>
          
         
        </el-table>
        
                <!-- 新增弹框 -->
                <el-dialog class="HanderPop" title="新增采购批次" :visible.sync="addHanderPop" >
                   

                  <el-rol :span="20" :offset="2">
                    <el-table
                      ref="multipleTable"
                      max-height="300"
                      tooltip-effect="dark"
                      @selection-change="handleSelectionChange"
                      :data="salesOrderData"
                      style="width: 100%; margin: 20px;">
                      
                      
                      <el-table-column
                        type="selection"
                        width="55">
                      </el-table-column>
                      
                      <el-table-column
                      prop="salesOrderNumber"
                      label="销售订单号">
                      </el-table-column>
                      <el-table-column
                      prop="salesDeliveryDate"
                      label="销售货期"
                      width="80">
                      </el-table-column>
                      <el-table-column
                      prop="salesDate"
                      label="销售日期"
                      width="160">
                      </el-table-column>
                      <el-table-column
                      prop="customerName"
                      label="客户名称"
                      width="120">
                      </el-table-column>
                     
                      <el-table-column
                        prop="remarks"
                        label="备注"
                        width="300"
                        style="height: 50px;">
                      </el-table-column>
                    </el-table>
                  </el-rol>
                  <el-form :model="form" :rules="rules" ref="form" :inline="true" label-position="right">
                    
                    <el-form-item label="采购员" :label-width="formLabelWidth" prop = "purchaser">
                      <el-select class="inputplace"
                       v-model="form.purchaser"
                        placeholder="请选择活动区域" >
                       
                        <el-option
                          v-for="item in this.purchaserDict"
                          :key="item.dictCode"
                          :label="item.dictLabel"
                          :value="item.dictLabel">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="采购日期" :label-width="formLabelWidth" prop = "purchaseDate"> 
                      <el-date-picker
                        class="inputplace"
                        style="width: 200px;"
                        v-model="form.purchaseDate"
                        align="right"
                        type="date"
                        placeholder="选择日期"
                        :picker-options="pickerOptionsdate"
                        value-format="yyyy-MM-dd"
                         clearable>
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item label="采购下单名称" :label-width="formLabelWidth"  prop = "orderName">
                      <el-input class="inputplace" 
                      v-model="form.orderName" ></el-input>
                    </el-form-item>
                    <el-form-item label="采购订单号" :label-width="formLabelWidth" prop = "orderNumber">
                      <el-input class="inputplace" 
                      v-model="form.orderNumber"></el-input>
                    </el-form-item>
                    
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="addHanderPop = false">取 消</el-button>
                    <el-button type="primary" @click="addtable('form')">确 定</el-button>
                  </div>
                  </el-dialog>  
                  <!-- 修改 -->
              
               <el-dialog class="HanderPop" title="修改采购批次" :visible.sync="editHanderPop" >
                   <el-form :model="editform" :rules="rules" ref="editform" :inline="true" label-position="right">
                     <el-form-item label="采购员" :label-width="formLabelWidth" prop = "purchaser">
                       <el-select class="inputplace"
                        v-model="editform.purchaser"
                         placeholder="请选择活动区域" >
                        
                         <el-option
                           v-for="item in this.purchaserDict"
                           :key="item.dictCode"
                           :label="item.dictLabel"
                           :value="item.dictLabel">
                         </el-option>
                       </el-select>
                     </el-form-item>
                     <el-form-item label="采购日期" :label-width="formLabelWidth" prop = "purchaseDate"> 
                       <el-date-picker
                         class="inputplace"
                         style="width: 200px;"
                         v-model="editform.purchaseDate"
                         align="right"
                         type="date"
                         placeholder="选择日期"
                         :picker-options="pickerOptionsdate"
                         value-format="yyyy-MM-dd"
                         clearable>

                       </el-date-picker>
                     </el-form-item>
                     <el-form-item label="采购下单名称" :label-width="formLabelWidth"  prop = "orderName">
                       <el-input class="inputplace" 
                       v-model="editform.orderName" ></el-input>
                     </el-form-item>
                     <el-form-item label="采购订单号" :label-width="formLabelWidth" prop = "orderNumber">
                       <el-input class="inputplace" 
                       v-model="editform.orderNumber"></el-input>
                     </el-form-item>
                   
                   </el-form>
                   <div slot="footer" class="dialog-footer">
                     <el-button @click="editHanderPop = false">取 消</el-button>
                     <el-button type="primary" @click="edittable('editform')">确 定</el-button>
                   </div>
                   </el-dialog>  
                  
                 <!-- 导入对话框 -->
                    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
                      <el-upload
                        ref="upload"
                        :limit="1"
                        accept=".xlsx, .xls"
                        :headers="upload.headers"
                        :action="upload.url"
                        :disabled="upload.isUploading"
                        :on-progress="handleFileUploadProgress"
                        :on-success="handleFileSuccess"
                        :auto-upload="false"
                        drag
                      >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip text-center" slot="tip">
                          <div class="el-upload__tip" slot="tip">
                            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                          </div>
                          <span>仅允许导入xls、xlsx格式文件。</span>
                          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate()">下载模板</el-link>
                        </div>
                      </el-upload>
                      <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitFileForm()">确 定</el-button>
                        <el-button @click="upload.open = false">取 消</el-button>
                      </div>
                    </el-dialog>
        </div>
        
      </div>
      <el-footer>
        <!-- 分页 -->
        <div class="pagination">
        <el-pagination
         
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.current"
          :page-sizes="[10, 20, 30, 50]"   
          :page-size="queryParams.Size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="countNum"
          > <!--分页Size   最大页数-->
        </el-pagination>
      </div>
      </el-footer>
  </div>
</template>





















<script>
import { getPurchaseBatchList,getPurchaseBatchid,getAllPurchaseBatch,getPurchaseBatchInsert,getPurchaseBatchEdit,getPurchaseBatchDelete,getPurchaseBatchCount} from "@/api/finance/PurchaseBatch/PurchaseBatch";
import { getSalesOrderList,getSalesOrderid,getAllSalesOrder,getSalesOrderInsert,getSalesOrderEdit,getSalesOrderDelete,getSalesOrderCount} from "@/api/finance/SalesOrder/SalesOrder";
import { listData } from "@/api/system/dict/data" 
import { getToken } from "@/utils/auth";
export default {
  inheritAttrs: false,
  components: {},
  props: [],
  data() {
    return {
      // 按钮可用
      editBotton:true,
      deleteBotton:true,
      // 表格数据
      tableData:[],
      salesOrderData:[],
      // 采购员数据
      purchaserDict:[],
      countNum:0,
      restaurants:[],
      restaurants1:[],
      queryParams:{
        purchaser:'',
        purchaseDate:'',
        orderName:'',
        orderNumber:'',
        
        size:10,
        pageNum:1,
        current:1,
      },
      formData: {
        mobile: '',
        field102: undefined,
        field103: false,
        field108: null,
        field107: undefined,
      },

      form: {
          purchaseId:undefined,
          purchaser:'',
          purchaseDate:'',
          orderName:'',
          orderNumber:'',
          
          createSource: this.$store.state.user.name,
          updateUser: this.$store.state.user.name
        },

      editform:{
          purchaseId:undefined,
          purchaser:undefined,
          purchaseDate:undefined,
          orderName:undefined,
          orderNumber:undefined,
          
          updateUser: this.$store.state.user.name
      },

      rules: {
        purchaser: [ { required: true, message: '请输入采购员', trigger: 'change' },],
        purchaseDate: [ { required: true, message: '请输入采购日期', trigger: 'blur' },],
        orderName: [ { required: true, message: '请输入订单名称', trigger: 'blur' },],
        orderNumber: [ { required: true, message: '请输入订单号', trigger: 'blur' },],
       
      

        // mobile: [{
        //   required: true,
        //   message: '请输入手机号',
        //   trigger: 'blur'
        // }, {
        //   pattern: /^1(3|4|5|7|8|9)\d{9}$/,
        //   message: '手机号格式错误',
        //   trigger: 'blur'
        // }],
        
        // field108: [{
        //   required: true,
        //   message: '请选择日期选择',
        //   trigger: 'change'
        // }],
      },

      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/finance/kltPurchaseBatch/importData"
      },
      pickerOptionsdate: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value1: '',
        field102Options:{},
        dialogTableVisible: false,
        // 页面
        addHanderPop: false,
        editHanderPop: false,
        uploadOpen:false,

        value2:'',
        formLabelWidth: '120px',
        // 下拉框数据
        queryFrom1:[],
        queryFrom2:[],
        //删除数据的id
        delIds:[]
    }
  },
  mounted() {
      this.restaurants = this.loadAll();
  },
  computed: {},
  watch: {},
  created() {
    //  获取当前时间
    var time = new Date();
    var day = ("0" + time.getDate()).slice(-2);
    var month = ("0" + (time.getMonth() + 1)).slice(-2);
    var today = time.getFullYear() + "-" + month + "-" + day;
    this.form.purchaseDate = today;
    
    
    getPurchaseBatchCount(this.queryParams).then(response => {
      this.countNum = response.data;
    });
    getPurchaseBatchList(this.queryParams).then(response => {
      this.tableData = response.data.records;
    });
    
    let query={
      pageNum: 1,
      pageSize: 10000,
    }
   
    getSalesOrderList(query).then(response => {
      this.salesOrderData = response.rows;
      console.log("1121212121212")
    });

//  拿取字典数据
    const queryParams1= {
        pageNum: undefined,
        pageSize: undefined,
        dictType: 'purchaser',
        dictLabel: undefined,
        status: undefined
      };
    listData(queryParams1).then(response => {
      this.purchaserDict = response.rows;
    });
    
    
  },
  methods: {
    // 重置表单
    resetForm() {
      for (let key in this.form) {
        if (this.form.hasOwnProperty(key)) {
          this.form[key] = null; // 或者使用 delete jsonObj[key];
        }
    }
    },
    // 添加数据
    addtable(formname){
      this.$refs[formname].validate((valid) => {
          if (valid) {

             getPurchaseBatchInsert(this.form).then(response => {
              this.addHanderPop = false;
            });
            this.$message({
              message: '添加成功',
              type: 'success'
            });
            
            getPurchaseBatchCount(this.queryParams).then(response => {
              this.countNum = response.data;
            });
            getPurchaseBatchList(this.queryParams).then(response => {
              this.tableData = response.data.records;
            }); 
            
          } else {
            this.open3();
          }
        });
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          this.resetForm();
        }, 500 * Math.random());
    },
    edittable(formname){
      this.$refs[formname].validate((valid) => {
          if (valid) {
            delete formname.createSource;
            getPurchaseBatchEdit(this.editform).then(response => {
              this.editHanderPop = false;
              
            });
            this.$message({
              message: '修改成功',
              type: 'success'
            });

            
            getPurchaseBatchList(this.queryParams).then(response => {
              this.tableData = response.data.records;
            }
            );  
          } else {
            this.open3();
          }
        });
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          this.resetForm();
        }, 500 * Math.random());
    },
    // 筛选下拉数据
    loadAll() {
      return []
    },


    // 订单名称筛选
    querySearchAsync(queryString, cb) {
        var restaurants = this.restaurants;       
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
    clearTimeout(this.timeout);
    this.restaurants=[];
        this.timeout = setTimeout(() => {
          getAllPurchaseBatch().then(response=>{
            response.data.forEach(item=>{
              this.restaurants.push({value:item.orderName,address:item.orderNumber})
            });
          })
          cb(results);
        }, 1000 * Math.random());
    },


    // 订单编号筛选
    querySearchAsync1(queryString, cb) {
        var restaurants1 = this.restaurants1;
        var results1 = queryString ? restaurants1.filter(this.createStateFilter(queryString)) : restaurants1;
    clearTimeout(this.timeout);
    this.restaurants1=[];
        this.timeout = setTimeout(() => {
          getAllPurchaseBatch().then(response=>{
            response.data.forEach(item=>{
              this.restaurants1.push({value:item.orderNumber,address:item.orderName})
            });
          })
          cb(results1);
        }, 1000 * Math.random());
    },


    createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
    },


    handleSelect(item) {
        // 选择内容并查询
        this.queryParams.orderName = item.value;
        this.getQueryFrom();
        
    },


    handleSelect2(item) {
        // 选择内容并查询
        this.queryParams.orderNumber = item.value;
        this.getQueryFrom();
        
    },
   

    getQueryFrom(){
      
      getPurchaseBatchCount(this.queryParams).then(response => {
              this.countNum = response.data;
            });
      getPurchaseBatchList(this.queryParams).then(response => {
              this.tableData = response.data.records;
            })
    },

    deletetable(){
      let idList  = this.delIds
      idList = JSON.parse(JSON.stringify(idList));
      if(idList.length>0){
        setTimeout(()=>{
        
        getPurchaseBatchDelete(idList).then(response => {
          if(response.data==true){
            console.log(response.date);
            getPurchaseBatchCount().then(response => {
              this.countNum = response.data;
            });
            getPurchaseBatchList(this.queryParams).then(response => {
              this.tableData = response.data.records;
            }); 
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }
      })
      },800)

      }
      
     
    },

    handleCurrentChange(val) {
       this.queryParams.current=val;
       console.log(val)
       getPurchaseBatchList(this.queryParams).then(response => {
      this.tableData = response.data.records;
    });
    },
    handleSizeChange(val) {
      this.queryParams.size=val;
      console.log(val)
      getPurchaseBatchList(this.queryParams).then(response => {
      this.tableData = response.data.records;
    });
      },
    getList() {
      this.loading = true;
      getPurchaseBatchList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },

    open3() {
        this.$message({
          message: '请检查信息是否填写完整',
          type: 'warning'
        });
      },
 
    onOpen() {},
    onClose() {
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.close()
      })
    },
   

     /** 下载模板操作 */
     importTemplate() {
      this.download('finance/kltPurchaseBatch/importTemplate', {
      }, `采购批次导入模板_${new Date().getTime()}.xlsx`)
    },

    // 导出数据
    importData() {
      this.download('finance/kltPurchaseBatch/export', {
          
      }, `采购批次数据导出_${new Date().getTime()}.xlsx`)
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
//  表格多选
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.delIds=[];
        // 判断选择行数
        if(val.length==1){

          this.multipleSelection = val;
        let aa = {
            purchaseId:val[0].purchaseId?val[0].purchaseId:'',
            purchaser:val[0].purchaser?val[0].purchaser:'',
            purchaseDate:val[0].purchaseDate?val[0].purchaseDate:'',
            orderName:val[0].orderName?val[0].orderName:'',
            orderNumber:val[0].orderNumber?val[0].orderNumber:'',
            
            updateUser: this.$store.state.user.name
          };
          this.delIds.push(val[0].purchaseId);
          this.editform=aa;
          this.editBotton=false;
          this.deleteBotton=false;
        }else if(val.length>0){
          for(let a=0;a<val.length;a++){
            this.delIds.push(val[a].purchaseId);
          }
          this.editBotton=true;
          this.deleteBotton=false;
        }else{
          this.editBotton=true;
          this.deleteBotton=true;
        }
      }
  }
}

</script>














<style>
.search{
    margin-top: 10px;
}
.infotable{
    margin-top: 10px;
    margin-left: 1%;
    margin-right: 1%;    
}
.infotable_handerchild{
    margin-top: 10px;
    margin-left: 40px;
}
.pagination{
  margin-right: 20px;    
    text-align :right;
}
.HanderPop{
  width:100%;
  display: inline-block;
}
.inputplace{
  width: 200px;
}
</style>